import React, {useState, useCallback, useRef, useEffect} from 'react';
import { CSSTransition } from 'react-transition-group';
import { connect } from 'react-redux';

import {Container,TopDesc,Menu,SongList,SongItem} from './style';
import  Header  from './../../baseUI/header/index';
import Scroll from '../../baseUI/scroll/index';
import { getName, getCount, isEmptyObject} from './../../api/utils';
import style from "../../assets/global-style";
import { HEADER_HEIGHT } from './../../api/config';
import {changeEnterLoading, getAlbumList} from "./store/actionCreators";
import Loading from "../../baseUI/loading";
import MusicNote from "../../baseUI/music-note/index";
import SongsList from "../SongsList";

function Album (props) {
  const [showStatus, setShowStatus] = useState (true);
  const [title, setTitle] = useState ("歌单");
  const [isMarquee, setIsMarquee] = useState (false);// 是否跑马灯
  const headerEl = useRef ();

  const id = props.match.params.id;

  const { currentAlbum:currentAlbumImmutable, enterLoading } = props;
  const { getAlbumDataDispatch } = props;
  const currentAlbum = currentAlbumImmutable.toJS();

  //点击一个专辑后,专辑的歌曲的数据是在这里初始化的 ---> currentAlbum
  //然后再点击一首歌 就会把这个专辑的所有歌 ---> changePlayListDispatch(songs)
  //并且设置currentSong
  //这样mini-player也就会显示出来
  useEffect (() => {
    getAlbumDataDispatch (id);
  }, [getAlbumDataDispatch, id]);


  const handleBack = useCallback(() => {
    setShowStatus(false);
  }, []);

  const handleScroll = useCallback((pos) => {
    let minScrollY = -HEADER_HEIGHT;
    let percent = Math.abs(pos.y / minScrollY);
    let headerDom = headerEl.current;
    //滑过顶部的高度开始变化
    if (pos.y < minScrollY) {
      headerDom.style.backgroundColor = style["theme-color"];
      headerDom.style.opacity = Math.min(1, (percent - 1) / 2);
      setTitle(currentAlbum.name);
      setIsMarquee(true);
    } else {
      headerDom.style.backgroundColor = "";
      headerDom.style.opacity = 1;
      setTitle("歌单");
      setIsMarquee(false);
    }
  }, [currentAlbum]);

  const musicNoteRef = useRef ();

  const musicAnimation = (x, y) => {
    musicNoteRef.current.startAnimation ({ x, y });
  };

  const renderTopDesc = () => {
    return (
      <TopDesc background={currentAlbum.coverImgUrl}>
        <div className="background">
          <div className="filter"></div>
        </div>
        <div className="img_wrapper">
          <div className="decorate"></div>
          <img src={currentAlbum.coverImgUrl} alt=""/>
          <div className="play_count">
            <i className="iconfont play">&#xe885;</i>
            <span className="count">{Math.floor (currentAlbum.subscribedCount/1000)/10} 万 </span>
          </div>
        </div>
        <div className="desc_wrapper">
          <div className="title">{currentAlbum.name}</div>
          <div className="person">
            <div className="avatar">
              <img src={currentAlbum.creator.avatarUrl} alt=""/>
            </div>
            <div className="name">{currentAlbum.creator.nickname}</div>
          </div>
        </div>
      </TopDesc>
    )
  }

  const renderMenu = () => {
    return (
      <Menu>
        <div>
          <i className="iconfont">&#xe6ad;</i>
          评论
        </div>
        <div>
          <i className="iconfont">&#xe86f;</i>
          点赞
        </div>
        <div>
          <i className="iconfont">&#xe62d;</i>
          收藏
        </div>
        <div>
          <i className="iconfont">&#xe606;</i>
          更多
        </div>
      </Menu>
    )
  };

  return (
    /** 注意onExited 我们会在动画结束时跳转路由
     * 即in被修改为false时*/
    /*
      那你可能会说,为什么不是直接在 handleBack 里面直接跳转路由呢？这里就是我踩过的一个坑,大家可以试试把 CSSTransition 中的 onExited 钩子删去,然后在 handleBack 中跳转路由。你会发现,动画根本就没有出现！

      让我来给你解释一下这是为什么,当你点击后,执行路由跳转逻辑,这个时候路由变化,当前的组件会被立即卸载,相关的动画当然也就不复存在了。最后我的解决方案就是,先让页面切出动画执行一次,然后在动画执行完的瞬间跳转路由,这就达到我们的预期了,这也就是现在呈现给大家的方案
    * */
    <CSSTransition
      in={showStatus}
      timeout={300}
      classNames="fly"
      appear={true}
      unmountOnExit
      onExited={props.history.goBack}
    >
      <Container>
        <Header ref={headerEl} title={title} handleClick={handleBack} isMarquee={isMarquee}/>
        {
          /*当页面进入 Ajax 请求还没有获取数据时，currentAlbum 的值为初始态 {}。直到数据异步加载完成，currentAlbum 才会改变，那么在这个过程中，通过 currentAlbum.creator 为 undefined，通过 current.creator.avatarUrl 取值自然会报错*/
          !isEmptyObject(currentAlbum) ? (
            <Scroll bounceTop={false} onScroll={handleScroll}>
              <div>
                {renderTopDesc()}
                {renderMenu()}
                <SongsList
                  songs={currentAlbum.tracks}
                  collectCount={currentAlbum.subscribedCount}
                  showCollect={true}
                  showBackground={true}
                  musicAnimation={musicAnimation}
                ></SongsList>
              </div>
            </Scroll>
          ) : null
        }
        { enterLoading ? <Loading></Loading> : null}
        <MusicNote ref={musicNoteRef}></MusicNote>
      </Container>
    </CSSTransition>
  );
}

// 映射 Redux 全局的 state 到组件的 props 上
const mapStateToProps = (state) => ({
  currentAlbum: state.getIn (['album', 'currentAlbum']),
  enterLoading: state.getIn (['album', 'enterLoading']),
});
// 映射 dispatch 到 props 上
const mapDispatchToProps = (dispatch) => {
  return {
    getAlbumDataDispatch (id) {
      dispatch (changeEnterLoading (true));
      dispatch (getAlbumList (id));
    },
  }
};

// 将 ui 组件包装成容器组件
export default connect (mapStateToProps, mapDispatchToProps)(React.memo (Album));
